<?php
/*
|--------------------------------------------------------------------------
| Admin.php
|--------------------------------------------------------------------------
| auther:Liutiansi
| Email:liutiansi@gmail.com
| update:2009-03-28
|
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class lvs extends Controller
{

/*
|--------------------------------------------------------------------------
| siteinfo Initialization;
|--------------------------------------------------------------------------
|
| include page head info、load library、default language...
| 
|
*/	
	private $data	    = array();
        private $Condition  = array();
	public function lvs()
	{
		parent::Controller();
                @session_start();
		$this->load->library('phpsession');	
                $this->load->library('bashlib');
		$this->load->model('admin_model');
		$this->load->database();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->helper('bash');
                if (strlen($this->phpsession->get('currlanguage'))==2){
                        $this->config->set_item('language',$this->phpsession->get('currlanguage')); 
                }
		$this->data['charset']	= $this->config->item('charset');
                $this->data['title']	= $this->config->item('title');
                $this->data['keywords']	= $this->config->item('keywords');
                $this->data['description']= $this->config->item('description');
		$this->data['webroot']= $this->config->item('webroot');
		$this->data['adminroot']= $this->config->item('adminroot');
                $this->data['lang']= $this->config->item('language');
                $this->lang->load('base',$this->config->item('language'));	
	}

        public function index()
        {
		//redirect('/lvs/Performance/lvsip');
		$this->Performance('lvsip');
            
        }



//||||||||||||||||||||||||||||||||||||||||||||||||||||||| DATACENTER ||||||||||||||||||||||||||||||||||||||||||||||||||||
	
/*
|--------------------------------------------------------------------------
|  DataCenter list page;
|--------------------------------------------------------------------------
|
| DataCenter list info page;.
| 
|
*/	
	public function DataCenters()
	{             
                parse_str($_SERVER['QUERY_STRING'],$_GET);

                if (!empty($_GET))
                        $this->data['serverip']=$_GET['serverip'];
                else
                        $this->data['serverip']="";
  
                if (empty($_GET['per_page']))
                        $this->data['per_page']=0;
                else
                        $this->data['per_page']=$_GET['per_page'];

                if ($this->data['serverip']!="")
                {
                        $this->Condition["wip"]=$this->data['serverip'];
                        $this->Condition["lip"]=$this->data['serverip'];
                }
                
                $this->load->library('pagination');
                $config['page_query_string'] = TRUE;
		$config['base_url']     = base_url().'/lvs/DataCenters?serverip='.$this->data['serverip'];;
 		$config['per_page']     = 100;
                $config['num_tag_open'] = '&nbsp;';
                $config['cur_tag_open'] = '&nbsp;<font class=pagenonor>';
                $config['cur_tag_close']= '</font>';
                $config['first_link']   = $this->lang->line('index_firepage');
                $config['last_link']    = $this->lang->line('index_lastpage');
                $config['next_link']    = $this->lang->line('index_nextpage');
                $config['prev_link']    = $this->lang->line('index_prevpage');
                $config['total_rows']   = $this->admin_model->Getcount_datacenter_all($this->Condition);
                $this->pagination->initialize($config);
                               
                $this->data['results']    = $this->admin_model->get_datacenter_results($config['per_page'],$this->data['per_page'],$this->Condition);
                $this->data['total_rows'] = $config['total_rows'];
                $this->data['alertinfo']  ="";
                $this->load->view("datacenter_view", $this->data);
	}



/*
|--------------------------------------------------------------------------
| Add/Edit focus page;
|--------------------------------------------------------------------------
|
| Add/Edit focus page ($tmp_id); //修改失败接收返回的ID，方便修改。
| 
|
*/
        public function datacenter_do($tmp_id=null)
        {
		if(strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !empty($_POST["selected_id"]) || $tmp_id!=null)
		{
			if ($tmp_id!=null)
				$ID=$tmp_id;
			else
				$ID=$_POST["selected_id"][0];
			$Condition["ID"]= $ID;
		        $myrow=$this->admin_model->datacenter_select_iddb($Condition);
		        if (!$myrow)
		        {
		                show_error("连接数据库出错，请与管理员联系。");
		        }
		        else
		        {
		                $this->data["ID"]= $ID;
		                $this->data["datacenter"]= $myrow['datacenter'];
				$this->data["gid"]= $myrow['gid'];
		                $this->data["wip"]= $myrow['wip'];
		                $this->data["lip"]= $myrow['lip'];
				$this->data["servername"]= $myrow['servername'];
				$this->data["state"]= $myrow['state'];
				$this->data["notification_email"]= $myrow['notification_email'];
				$this->data["notification_email_from"]= $myrow['notification_email_from'];
				$this->data["smtp_server"]= $myrow['smtp_server'];
				$this->data["smtp_connect_timeout"]= $myrow['smtp_connect_timeout'];
				$this->data["router_id"]= $myrow['router_id'];
				$this->data["interface"]= $myrow['interface'];
				$this->data["lvs_sync_daemon_inteface"]= $myrow['lvs_sync_daemon_inteface'];
				$this->data["virtual_router_id"]= $myrow['virtual_router_id'];
				$this->data["priority"]= $myrow['priority'];
				$this->data["advert_int"]= $myrow['advert_int'];
				$this->data["auth_type"]= $myrow['auth_type'];
				$this->data["auth_pass"]= $myrow['auth_pass'];
		                unset($this->admin_model, $myrow);
		        }
		}
		$this->load->view('datacenter_do_view', $this->data);
        }


/*
|--------------------------------------------------------------------------
| check datacenter form;
|--------------------------------------------------------------------------
|
|  heck datacenter form code.
| 
|
*/		
	function _is_check_datacenter($ID="")
 	{
		if ($ID=="")
			$_unique_class="callback__is_unique";
		else
			$_unique_class="callback__is_unique[".$ID."]";
		$this->load->library('validation');
		$this->validation->set_error_delimiters('<span class="errortext">','</span>');
		$rules['datacenter']  = "trim|required|max_length[20]";
		$rules['gid']  = "trim|required|numeric|max_length[2]";
		$rules['wip']   = "trim|required|valid_ip|".$_unique_class;
		$rules['lip']   = "trim|required|valid_ip|".$_unique_class;
		$rules['servername']  = "trim|required|max_length[20]";
		$rules['notification_email']   = "trim|required|valid_email";
		$rules['notification_email_from']   = "trim|required|valid_email";
		$rules['smtp_server']	= "trim|required|max_length[15]";
		$rules['smtp_connect_timeout']	= "trim|required|numeric|max_length[2]";
		$rules['router_id']	= "trim|required|max_length[10]";
		$rules['interface']	= "trim|required|max_length[5]";
		$rules['lvs_sync_daemon_inteface']	= "trim|required|max_length[5]";
		$rules['virtual_router_id']	= "trim|required|numeric|max_length[2]";
		$rules['priority']	= "trim|required|numeric|max_length[3]";
		$rules['advert_int']	= "trim|required|numeric|max_length[2]";
		$rules['auth_type']	= "trim|required|max_length[5]";
		$rules['auth_pass']	= "trim|required|max_length[5]";
		
		$this->validation->set_rules($rules);

		$fields['datacenter']  ='数据中心名称';
		$fields['gid']  ='组ID';
		$fields['wip']	="服务IP";
		$fields['lip']	="通讯IP";
		$fields['servername']	="主机名称";
		$fields['notification_email']	="通知邮件";
		$fields['notification_email_from']	="邮件发送人";
		$fields['smtp_server']	="SMTP服务器";
		$fields['smtp_connect_timeout']	="SMTP超时";
		$fields['router_id']	="路由ID";
		$fields['interface']	="服务设备接口";
		$fields['lvs_sync_daemon_inteface']	="探测设备接口";
		$fields['virtual_router_id']	="虚拟路由ID";
		$fields['priority']	="优先权";
		$fields['advert_int']	="同步通知间隔";
		$fields['auth_type']	="验证类型";
		$fields['auth_pass']	="验证密码";
		
		$this->validation->set_fields($fields);

		if ($this->validation->run() == false)
		{
			return false;
		}
		else
		{
                        return true;
		}
 	}

/*
|--------------------------------------------------------------------------
| check datacenter form's IP Exist?
|--------------------------------------------------------------------------
|
|  check ip(w/l) does Exist by user_model->_datacenter_is_uniqu.
| 
|
*/	 	
	public function _is_unique($ipstr,$ID="")
	{
		if(!empty($ipstr))
		{
			$this->validation->set_message('_is_unique', "'".$ipstr."'已经存在了。");
			return $this->admin_model->_datacenter_is_unique($ipstr,$ID);
		}
	}
	
	
/*
|--------------------------------------------------------------------------
| Add post datacenter page;
|--------------------------------------------------------------------------
|
| Add post datacenter page;
| 
|
*/
        public function datacenter_do_add()
        {
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }                
                if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
		{
			if($this->_is_check_datacenter())
			{
                                $this->load->library('inputfilter');
				
				$data['datacenter']   = $this->validation->datacenter;
				$data['state']   = $_POST["state"];
				$data['gid']    = $this->validation->gid;
                                $data['wip']    = $this->validation->wip;
  				$data['lip']= $this->validation->lip;
				$data['servername']= $this->validation->servername;
				
				$data['notification_email']= $this->validation->notification_email;
				$data['notification_email_from']= $this->validation->notification_email_from;
				$data['smtp_server']= $this->validation->smtp_server;
				$data['smtp_connect_timeout']= $this->validation->smtp_connect_timeout;
				$data['router_id']= $this->validation->router_id;
				$data['interface']= $this->validation->interface;
				$data['lvs_sync_daemon_inteface']= $this->validation->lvs_sync_daemon_inteface;
				$data['virtual_router_id']= $this->validation->virtual_router_id;
				$data['priority']= $this->validation->priority;
				$data['advert_int']= $this->validation->advert_int;
				$data['auth_type']= $this->validation->auth_type;
				$data['auth_pass']= $this->validation->auth_pass;
				
     				//check ok,the data update db;
      				if ($this->admin_model->datacenter_postdb($data)==1)
                                {
                                        if ($data['state']=="MASTER")
					{
						$lvsdir = './LVS/'.$data['wip'];
						if (!file_exists($lvsdir))
						{
							mkdir($lvsdir, 0755);
							mkdir($lvsdir."/master", 0755);
							mkdir($lvsdir."/backup", 0755);
							mkdir($lvsdir."/performance", 0755);
							mkdir('./images/LVS/'.$data['wip'], 0755);
						}
					}
					redirect("/lvs/DataCenters");
                                }
                                else
                                {
                                        show_error("db error!");
                                }
                        }
                        else
                        {
				$this->datacenter_do();
                        }

		}
        }
	
	

/*
|--------------------------------------------------------------------------
| Edit post focus page;
|--------------------------------------------------------------------------
|
| Edit post focus page;
| 
|
*/
        public function datacenter_do_edit()
        {
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }                  
                if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
		{
			$ID=$_POST["ID"];
			if($this->_is_check_datacenter($ID))
			{
                                $this->load->library('inputfilter');
				$data['datacenter']   = $this->validation->datacenter;
				$data['state']   = $_POST["state"];
				$data['gid']    = $this->validation->gid;
                                $data['wip']    = $this->validation->wip;
  				$data['lip']= $this->validation->lip;
				$data['servername']= $this->validation->servername;
				
				$data['notification_email']= $this->validation->notification_email;
				$data['notification_email_from']= $this->validation->notification_email_from;
				$data['smtp_server']= $this->validation->smtp_server;
				$data['smtp_connect_timeout']= $this->validation->smtp_connect_timeout;
				$data['router_id']= $this->validation->router_id;
				$data['interface']= $this->validation->interface;
				$data['lvs_sync_daemon_inteface']= $this->validation->lvs_sync_daemon_inteface;
				$data['virtual_router_id']= $this->validation->virtual_router_id;
				$data['priority']= $this->validation->priority;
				$data['advert_int']= $this->validation->advert_int;
				$data['auth_type']= $this->validation->auth_type;
				$data['auth_pass']= $this->validation->auth_pass;

     				//check ok,the data update db;
      				if ($this->admin_model->datacenter_editdb($data,$ID)==1)
                                {
                                        redirect("/lvs/DataCenters");
                                }
                                else
                                {
                                        show_error("db error!");
                                }
                        }
                        else
                        {
				//传递ID到FocusServer_do，方便读取信息修改
				$this->datacenter_do($ID);
                        }

		}
        }





//||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| VIP |||||||||||||||||||||||||||||||||||||||||||||||||||
/*
|--------------------------------------------------------------------------
|  VIP list page;
|--------------------------------------------------------------------------
|
| VIP list info page;.
| 
|
*/	
	public function VIP($lvsip="")
	{             
                parse_str($_SERVER['QUERY_STRING'],$_GET);

                if (!empty($_GET))
		{
                        $this->data['serverip']=$_GET['serverip'];
			$lvsip=$_GET['lvsip'];
		}
                else
                        $this->data['serverip']="";
  
                if (empty($_GET['per_page']))
                        $this->data['per_page']=0;
                else
                        $this->data['per_page']=$_GET['per_page'];
		
		if ($lvsip!="")
			$this->Condition["datacenter_id"]=$lvsip;
			
                if ($this->data['serverip']!="")
                {
                        $this->Condition["virtual_ipaddress"]=$this->data['serverip'];  
                }
                
                $this->load->library('pagination');
                $config['page_query_string'] = TRUE;
		$config['base_url']     = base_url().'/lvs/VIP?serverip='.$this->data['serverip'].'&lvsip='.$lvsip;
 		$config['per_page']     = 100;
                $config['num_tag_open'] = '&nbsp;';
                $config['cur_tag_open'] = '&nbsp;<font class=pagenonor>';
                $config['cur_tag_close']= '</font>';
                $config['first_link']   = $this->lang->line('index_firepage');
                $config['last_link']    = $this->lang->line('index_lastpage');
                $config['next_link']    = $this->lang->line('index_nextpage');
                $config['prev_link']    = $this->lang->line('index_prevpage');
                $config['total_rows']   = $this->admin_model->Getcount_VIP_all($this->Condition);
                $this->pagination->initialize($config);
                               
                $this->data['results']    = $this->admin_model->get_VIP_results($config['per_page'],$this->data['per_page'],$this->Condition);
                $this->data['total_rows'] = $config['total_rows'];
                $this->data['alertinfo']  ="";
                $this->load->view("VIP_view", $this->data);
	}



/*
|--------------------------------------------------------------------------
| Add/Edit VIP page;
|--------------------------------------------------------------------------
|
| Add/Edit VIP page ($tmp_id); //修改失败接收返回的ID，方便修改。
| 
|
*/
        public function VIP_do($tmp_id=null)
        {
		if(strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !empty($_POST["selected_id"]) || $tmp_id!=null)
		{
			if ($tmp_id!=null)
				$ID=$tmp_id;
			else
				$ID=$_POST["selected_id"][0];
			$Condition["ID"]= $ID;
		        $myrow=$this->admin_model->VIP_select_iddb($Condition);
		        if (!$myrow)
		        {
		                show_error("连接数据库出错，请与管理员联系。");
		        }
		        else
		        {
		                $this->data["ID"]= $ID;
				$this->data["datacenter_id"]= $myrow['datacenter_id'];
		                $this->data["virtual_ipaddress"]= $myrow['virtual_ipaddress'];
				$this->data["port"]= $myrow['port'];
				$this->data["app"]= $myrow['app'];
				$this->data["delay_loop"]= $myrow['delay_loop'];
		                $this->data["lb_algo"]= $myrow['lb_algo'];
		                $this->data["lb_kind"]= $myrow['lb_kind'];
				$this->data["protocol"]= $myrow['protocol'];
		                //unset($this->admin_model, $myrow);
		        }
		}
		$this->load->view('VIP_do_view', $this->data);
        }


/*
|--------------------------------------------------------------------------
| check datacenter form;
|--------------------------------------------------------------------------
|
|  heck datacenter form code.
| 
|
*/		
	function _is_check_VIP($ID="")
 	{
		if ($ID=="")
			$_unique_class="callback__VIP_is_unique";
		else
			$_unique_class="callback__VIP_is_unique[".$ID."]";
		$this->load->library('validation');
		$this->validation->set_error_delimiters('<span class="errortext">','</span>');
		$rules['virtual_ipaddress']   = "trim|required|valid_ip|".$_unique_class;
		$rules['app']   = "trim|required|max_length[50]";
		$rules['port']   = "trim|required|numeric|max_length[5]";
		$rules['delay_loop']   = "trim|required|numeric|max_length[3]";
		$rules['persistence_timeout']	= "trim|required|numeric|max_length[3]";
		
		$this->validation->set_rules($rules);

		$fields['virtual_ipaddress']  ='VIP';
		$fields['app']  ='应用名称';
		$fields['app']  ='服务端口';
		$fields['delay_loop']	="健康检查间隔(s)";
		$fields['persistence_timeout']	="会话保持时间(s)";


		
		$this->validation->set_fields($fields);

		if ($this->validation->run() == false)
		{
			return false;
		}
		else
		{
                        return true;
		}
 	}

/*
|--------------------------------------------------------------------------
| check datacenter form's IP Exist?
|--------------------------------------------------------------------------
|
|  check ip(w/l) does Exist by user_model->_datacenter_is_uniqu.
| 
|
*/	 	
	public function _VIP_is_unique($ipstr,$ID="")
	{
		if(!empty($ipstr))
		{
			$this->validation->set_message('_VIP_is_unique', "'".$ipstr."'已经存在了。");
			return $this->admin_model->_VIP_is_unique($ipstr,$ID);
		}
	}
	
	
/*
|--------------------------------------------------------------------------
| Add post datacenter page;
|--------------------------------------------------------------------------
|
| Add post datacenter page;
| 
|
*/
        public function VIP_do_add()
        {
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }                
                if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
		{
			if($this->_is_check_VIP())
			{
                                $this->load->library('inputfilter');
				
				$data['datacenter_id']   = $_POST["datacenter_id"];
				$data['lb_algo']   = $_POST["lb_algo"];
				$data['lb_kind']   = $_POST["lb_kind"];
				$data['protocol']   = $_POST["protocol"];
				
				$data['virtual_ipaddress']    = $this->validation->virtual_ipaddress;
				$data['app']    = $this->validation->app;
				$data['port']    = $this->validation->port;
                                $data['delay_loop']    = $this->validation->delay_loop;
  				$data['persistence_timeout']= $this->validation->persistence_timeout;
				
     				//check ok,the data update db;
      				if ($this->admin_model->VIP_postdb($data)==1)
                                {
                                        redirect("/lvs/VIP");
                                }
                                else
                                {
                                        show_error("db error!");
                                }
                        }
                        else
                        {
				$this->VIP_do();
                        }

		}
        }
	
	

/*
|--------------------------------------------------------------------------
| Edit post focus page;
|--------------------------------------------------------------------------
|
| Edit post focus page;
| 
|
*/
        public function VIP_do_edit()
        {
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }                  
                if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
		{
			$ID=$_POST["ID"];
			if($this->_is_check_VIP($ID))
			{
                                $this->load->library('inputfilter');
				$data['datacenter_id']   = $_POST["datacenter_id"];
				$data['lb_algo']   = $_POST["lb_algo"];
				$data['lb_kind']   = $_POST["lb_kind"];
				$data['protocol']   = $_POST["protocol"];
				
				$data['virtual_ipaddress']    = $this->validation->virtual_ipaddress;
                                $data['delay_loop']    = $this->validation->delay_loop;
				$data['app']    = $this->validation->app;
				$data['port']    = $this->validation->port;
  				$data['persistence_timeout']= $this->validation->persistence_timeout;

     				//check ok,the data update db;
      				if ($this->admin_model->VIP_editdb($data,$ID)==1)
                                {
                                        redirect("/lvs/VIP");
                                }
                                else
                                {
                                        show_error("db error!");
                                }
                        }
                        else
                        {
				//传递ID到FocusServer_do，方便读取信息修改
				$this->VIP_do($ID);
                        }

		}
        }


//||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Servers |||||||||||||||||||||||||||||||||||||||||||||||||||
/*
|--------------------------------------------------------------------------
|  Servers list page;
|--------------------------------------------------------------------------
|
| Servers list info page;.
| 
|
*/	
	public function Servers($vipip="")
	{             
                parse_str($_SERVER['QUERY_STRING'],$_GET);

                if (!empty($_GET))
		{
                        $this->data['serverip']=$_GET['serverip'];
			$vipip=$_GET['vipip'];
		}
                else
                        $this->data['serverip']="";
  
                if (empty($_GET['per_page']))
                        $this->data['per_page']=0;
                else
                        $this->data['per_page']=$_GET['per_page'];
		
		if ($vipip!="")
			$this->Condition["VIP"]=$vipip;
			
                if ($this->data['serverip']!="")
                {
                        $this->Condition["serverip"]=$this->data['serverip'];  
                }
                
                $this->load->library('pagination');
                $config['page_query_string'] = TRUE;
		$config['base_url']     = base_url().'/lvs/Servers?serverip='.$this->data['serverip'].'&vipip='.$vipip;
 		$config['per_page']     = 8;
                $config['num_tag_open'] = '&nbsp;';
                $config['cur_tag_open'] = '&nbsp;<font class=pagenonor>';
                $config['cur_tag_close']= '</font>';
                $config['first_link']   = $this->lang->line('index_firepage');
                $config['last_link']    = $this->lang->line('index_lastpage');
                $config['next_link']    = $this->lang->line('index_nextpage');
                $config['prev_link']    = $this->lang->line('index_prevpage');
                $config['total_rows']   = $this->admin_model->Getcount_Servers_all($this->Condition);
                $this->pagination->initialize($config);
                               
                $this->data['results']    = $this->admin_model->get_Servers_results($config['per_page'],$this->data['per_page'],$this->Condition);
                $this->data['total_rows'] = $config['total_rows'];
                $this->data['alertinfo']  ="";
                $this->load->view("Servers_view", $this->data);
	}



/*
|--------------------------------------------------------------------------
| Add/Edit Servers page;
|--------------------------------------------------------------------------
|
| Add/Edit Servers page ($tmp_id); //修改失败接收返回的ID，方便修改。
| 
|
*/
        public function Servers_do($tmp_id=null)
        {
		if(strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !empty($_POST["selected_id"]) || $tmp_id!=null)
		{
			if ($tmp_id!=null)
				$ID=$tmp_id;
			else
				$ID=$_POST["selected_id"][0];
			$Condition["ID"]= $ID;
		        $myrow=$this->admin_model->Servers_select_iddb($Condition);
		        if (!$myrow)
		        {
		                show_error("连接数据库出错，请与管理员联系。");
		        }
		        else
		        {
		                $this->data["ID"]= $ID;
				$this->data["VIP"]= $myrow['VIP'];
		                $this->data["serverip"]= $myrow['serverip'];
				$this->data["serverlip"]= $myrow['serverlip'];
				$this->data["servername"]= $myrow['servername'];
				$this->data["port"]= $myrow['port'];
		                $this->data["weight"]= $myrow['weight'];
		                $this->data["Monitors"]= $myrow['Monitors'];
		                //unset($this->admin_model, $myrow);
		        }
		}
		$this->load->view('Servers_do_view', $this->data);
        }


/*
|--------------------------------------------------------------------------
| check Servers form;
|--------------------------------------------------------------------------
|
|  heck Servers form code.
| 
|
*/		
	function _is_check_Servers($ID="")
 	{
		if ($ID=="")
			$_unique_class="callback__Servers_is_unique";
		else
			$_unique_class="callback__Servers_is_unique[".$ID."]";
		$this->load->library('validation');
		$this->validation->set_error_delimiters('<span class="errortext">','</span>');
		$rules['serverip']   = "trim|required|valid_ip|".$_unique_class;
		$rules['serverlip']   = "trim|required|valid_ip|".$_unique_class;
		$rules['servername']   = "trim|required|max_length[20]";
		$rules['port']   = "trim|required|numeric|max_length[5]";
		$rules['weight']	= "trim|required|numeric|max_length[3]";
		
		$this->validation->set_rules($rules);

		$fields['serverip']  	='服务IP';
		$fields['serverlip']  	='通讯IP';
		$fields['servername']  	='主机名称';
		$fields['port']		="服务器端口";
		$fields['weight']	="权重";


		
		$this->validation->set_fields($fields);

		if ($this->validation->run() == false)
		{
			return false;
		}
		else
		{
                        return true;
		}
 	}

/*
|--------------------------------------------------------------------------
| check Servers form's IP Exist?
|--------------------------------------------------------------------------
|
|  check ip(w/l) does Exist by user_model->_datacenter_is_uniqu.
| 
|
*/	 	
	public function _Servers_is_unique($ipstr,$ID="")
	{
		if(!empty($ipstr))
		{
			$this->validation->set_message('_Servers_is_unique', "'".$ipstr."'已经存在了。");
			return $this->admin_model->_Servers_is_unique($ipstr,$ID);
		}
	}
	
	
/*
|--------------------------------------------------------------------------
| Add post Servers page;
|--------------------------------------------------------------------------
|
| Add post Servers page;
| 
|
*/
        public function Servers_do_add()
        {
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }                
                if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
		{
			if($this->_is_check_Servers())
			{
                                $this->load->library('inputfilter');
				
				$data['VIP']   = $_POST["VIP"];
				$data['Monitors']   = $_POST["Monitors"];
				
				$data['serverip']    = $this->validation->serverip;
				$data['serverlip']    = $this->validation->serverlip;
				$data['servername']    = $this->validation->servername;
                                $data['port']    = $this->validation->port;
  				$data['weight']= $this->validation->weight;
				
     				//check ok,the data update db;
      				if ($this->admin_model->Servers_postdb($data)==1)
                                {
                                        redirect("/lvs/Servers");
                                }
                                else
                                {
                                        show_error("db error!");
                                }
                        }
                        else
                        {
				$this->Servers_do();
                        }

		}
        }
	
	

/*
|--------------------------------------------------------------------------
| Edit post Servers page;
|--------------------------------------------------------------------------
|
| Edit post Servers page;
| 
|
*/
        public function Servers_do_edit()
        {
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }                  
                if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
		{
			$ID=$_POST["ID"];
			if($this->_is_check_Servers($ID))
			{
                                $this->load->library('inputfilter');
				$data['VIP']   = $_POST["VIP"];
				$data['Monitors']   = $_POST["Monitors"];
				
				$data['serverip']    = $this->validation->serverip;
				$data['serverlip']    = $this->validation->serverlip;
				$data['servername']    = $this->validation->servername;
                                $data['port']    = $this->validation->port;
  				$data['weight']= $this->validation->weight;

     				//check ok,the data update db;
      				if ($this->admin_model->Servers_editdb($data,$ID)==1)
                                {
                                        redirect("/lvs/Servers");
                                }
                                else
                                {
                                        show_error("db error!");
                                }
                        }
                        else
                        {
				//传递ID到FocusServer_do，方便读取信息修改
				$this->Servers_do($ID);
                        }

		}
        }



//||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Monitors |||||||||||||||||||||||||||||||||||||||||||||||||||
/*
|--------------------------------------------------------------------------
|  Monitors list page;
|--------------------------------------------------------------------------
|
| Monitors list info page;.
| 
|
*/	
	public function Monitors()
	{             
                parse_str($_SERVER['QUERY_STRING'],$_GET);

                if (!empty($_GET))
		{
                        $this->data['serverip']=$_GET['serverip'];
		}
                else
                        $this->data['serverip']="";
  
                if (empty($_GET['per_page']))
                        $this->data['per_page']=0;
                else
                        $this->data['per_page']=$_GET['per_page'];
		
			
                if ($this->data['serverip']!="")
                {
                        $this->Condition["monitors_name"]=$this->data['serverip'];  
                }
                
                $this->load->library('pagination');
                $config['page_query_string'] = TRUE;
		$config['base_url']     = base_url().'/lvs/Monitors?serverip='.$this->data['serverip'];
 		$config['per_page']     = 50;
                $config['num_tag_open'] = '&nbsp;';
                $config['cur_tag_open'] = '&nbsp;<font class=pagenonor>';
                $config['cur_tag_close']= '</font>';
                $config['first_link']   = $this->lang->line('index_firepage');
                $config['last_link']    = $this->lang->line('index_lastpage');
                $config['next_link']    = $this->lang->line('index_nextpage');
                $config['prev_link']    = $this->lang->line('index_prevpage');
                $config['total_rows']   = $this->admin_model->Getcount_Monitors_all($this->Condition);
                $this->pagination->initialize($config);
                               
                $this->data['results']    = $this->admin_model->get_Monitors_results($config['per_page'],$this->data['per_page'],$this->Condition);
                $this->data['total_rows'] = $config['total_rows'];
                $this->data['alertinfo']  ="";
                $this->load->view("Monitors_view", $this->data);
	}



/*
|--------------------------------------------------------------------------
| Add/Edit Monitors page;
|--------------------------------------------------------------------------
|
| Add/Edit Monitors page ($tmp_id); //修改失败接收返回的ID，方便修改。
| 
|
*/
        public function Monitors_do($tmp_id=null)
        {
		if(strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !empty($_POST["selected_id"]) || $tmp_id!=null)
		{
			if ($tmp_id!=null)
				$ID=$tmp_id;
			else
				$ID=$_POST["selected_id"][0];
			$Condition["ID"]= $ID;
		        $myrow=$this->admin_model->Monitors_select_iddb($Condition);
		        if (!$myrow)
		        {
		                show_error("连接数据库出错，请与管理员联系。");
		        }
		        else
		        {
		                $this->data["ID"]= $ID;
				$this->data["monitors_name"]= $myrow['monitors_name'];
		                $this->data["monitors_type"]= $myrow['monitors_type'];
				$this->data["monitors_par1"]= $myrow['monitors_par1'];
		                $this->data["monitors_par2"]= $myrow['monitors_par2'];
		        }
		}
		$this->load->view('Monitors_do_view', $this->data);
        }


/*
|--------------------------------------------------------------------------
| check Monitors form;
|--------------------------------------------------------------------------
|
|  heck Monitors form code.
| 
|
*/		
	function _is_check_Monitors($ID="")
 	{
		if ($ID=="")
			$_unique_class="callback__Monitors_is_unique";
		else
			$_unique_class="callback__Monitors_is_unique[".$ID."]";
		$this->load->library('validation');
		$this->validation->set_error_delimiters('<span class="errortext">','</span>');
		$rules['monitors_name']   = "trim|required|max_length[20]".$_unique_class;
		$rules['monitors_par1']   = "trim|required|max_length[200]";
		$rules['monitors_par2']	= "trim|required|max_length[200]";
		
		$this->validation->set_rules($rules);

		$fields['virtual_ipaddress']  ='监控名称';
		$fields['monitors_par1']	="参数1";
		$fields['monitors_par2']	="参数2";


		
		$this->validation->set_fields($fields);

		if ($this->validation->run() == false)
		{
			return false;
		}
		else
		{
                        return true;
		}
 	}

/*
|--------------------------------------------------------------------------
| check Monitors form's IP Exist?
|--------------------------------------------------------------------------
|
|  check ip(w/l) does Exist by user_model->_datacenter_is_uniqu.
| 
|
*/	 	
	public function _Monitors_is_unique($ipstr,$ID="")
	{
		if(!empty($ipstr))
		{
			$this->validation->set_message('_Monitors_is_unique', "'".$ipstr."'已经存在了。");
			return $this->admin_model->_Monitors_is_unique($ipstr,$ID);
		}
	}
	
	
/*
|--------------------------------------------------------------------------
| Add post Monitors page;
|--------------------------------------------------------------------------
|
| Add post Monitors page;
| 
|
*/
        public function Monitors_do_add()
        {
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }                
                if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
		{
			if($this->_is_check_Monitors())
			{
                                $this->load->library('inputfilter');
				
				$data['monitors_type']   = $_POST["monitors_type"];
				
				$data['monitors_name']    = $this->validation->monitors_name;
                                $data['monitors_par1']    = $this->validation->monitors_par1;
  				$data['monitors_par2']	  = $this->validation->monitors_par2;
				
     				//check ok,the data update db;
      				if ($this->admin_model->Monitors_postdb($data)==1)
                                {
                                        redirect("/lvs/Monitors");
                                }
                                else
                                {
                                        show_error("db error!");
                                }
                        }
                        else
                        {
				$this->Monitors_do();
                        }

		}
        }
	
	

/*
|--------------------------------------------------------------------------
| Edit post Monitors page;
|--------------------------------------------------------------------------
|
| Edit post Monitors page;
| 
|
*/
        public function Monitors_do_edit()
        {
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }                  
                if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
		{
			$ID=$_POST["ID"];
			if($this->_is_check_Monitors($ID))
			{
                                $this->load->library('inputfilter');
				$data['monitors_type']   = $_POST["monitors_type"];
				
				$data['monitors_name']    = $this->validation->monitors_name;
                                $data['monitors_par1']    = $this->validation->monitors_par1;
  				$data['monitors_par2']	  = $this->validation->monitors_par2;

     				//check ok,the data update db;
      				if ($this->admin_model->Monitors_editdb($data,$ID)==1)
                                {
                                        redirect("/lvs/Monitors");
                                }
                                else
                                {
                                        show_error("db error!");
                                }
                        }
                        else
                        {
				//传递ID到FocusServer_do，方便读取信息修改
				$this->Monitors_do($ID);
                        }

		}
        }


/*
|--------------------------------------------------------------------------
|  del Monitors page;
|--------------------------------------------------------------------------
|
| del Monitors page;.
| 
|
*/	
	public function Monitors_do_del()
	{
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }
                if (empty($_POST['selected_id']))
                        show_error("/lvs/Monitors|".$this->lang->line('admin_noselect'));
                else
                        $this->Condition=$_POST['selected_id'];
					
		if (!$this->admin_model->_Monitors_is_server_unique($this->Condition))
		{
			show_error("/lvs/Monitors|该监控规则已经被引用，不能删除！");
		}

                if ($this->admin_model->set_delete('ty_lvs_monitors',$this->Condition))
                        $this->data['alertinfo']  ="数据删除成功！";
                else
                        $this->data['alertinfo']  ="数据删除失败！";
		redirect('/lvs/Monitors');
	}
	
	

/*
|--------------------------------------------------------------------------
|  return Monitors_parname;
|--------------------------------------------------------------------------
|
| Monitors_parname;.
| 
|
*/	
	public function Monitors_parname($partype="")
	{
		echo "{\n";
		echo "        \"Monitors\": [\n";
		echo "                {\n";
		echo "			\"par1\": \"".MonitorsParname($partype,'1')."\",\n";
		echo "			\"par2\": \"".MonitorsParname($partype,'2')."\"\n";
		echo "                },\n";
		echo "        ]\n";
		echo "}\n";		
	}
	
	
/*
|--------------------------------------------------------------------------
|  return Monitors_digest;
|--------------------------------------------------------------------------
|
| Monitors_digest;.
| 
|
*/	
	public function Monitors_digest()
	{
		parse_str($_SERVER['QUERY_STRING'],$_GET);
		$ip=$_GET["ip"];
		$path=$_GET["path"];
		$str=system("/usr/bin/genhash -s ".$ip." -p 80 -u ".$path."|awk '{print $3}'");	
	}

	
/*
|--------------------------------------------------------------------------
|   Production keepalived Config;
|--------------------------------------------------------------------------
|
|  Production keepalived Config
| 
|
*/	
	public function Production_config($lvsip,$status='m',$servername='')
	{
		$configstr=$this->admin_model->ProductionConfig($lvsip,'m');
		$filename="./LVS/".$lvsip."/master/keepalived.conf";
		$data=$configstr;
		writeFile($filename,$data);
		
		$configstr=$this->admin_model->ProductionConfig($lvsip,'b');
		$filename="./LVS/".$lvsip."/backup/keepalived.conf";
		$data=$configstr;
		writeFile($filename,$data);
		echo "<table width=\"300\"  border=\"0\" cellpadding=\"2\" cellspacing=\"1\" bgcolor=\"#006699\"><tr height=50 align=center bgcolor=\"#DFFFFF\"><td><font color=green>恭喜你，配置生成成功！</font></td></tr></table>\n";

	}

	
/*
|--------------------------------------------------------------------------
|   Reload_config keepalived Config;
|--------------------------------------------------------------------------
|
|  Reload_config keepalived Config
| 
|
*/	
	public function Reload_config($lvsip,$status='m',$servername='')
	{
		$bashpath=$this->data['webroot']."/LVS/";
		$str="<br>";
		$ServerInfo=$servername."*".$lvsip;
		if ($status=="m")
		{
			$sys_param_1="master";
			$sys_param_2=$bashpath.$lvsip."/master/keepalived.conf";
		}
		elseif ($status=="b")
		{
			$sys_param_1="backup";
			$sys_param_2=$bashpath.$this->admin_model->get_MASTER_IP($lvsip)."/backup/keepalived.conf";
		}
		else	show_error("参数错误，中止！");
		
		exec("/usr/local/bin/python ".$this->data['adminroot']."/ModuleClass.py 8888 ".$ServerInfo." ".$sys_param_1." ".$sys_param_2, $ar, $status);
		for ($i=0; $i < count($ar);$i++)
			if ($i==0)
				$str.=str_replace('ffffff', 'green',$ar[$i])."<br>";
			else
				$str.=$ar[$i]."<br>";
		$str = substr($str,0,strlen($str)-4);
		echo "<table width=\"300\"  border=\"0\" cellpadding=\"2\" cellspacing=\"1\" bgcolor=\"#006699\"><tr height=50 align=center bgcolor=\"#DFFFFF\"><td><font color=green>".$str."</font></td></tr></table>\n";

	}


/*
|--------------------------------------------------------------------------
|   Reload_realserver realserver.sh Config;
|--------------------------------------------------------------------------
|
|  Reload_realserver realserver.sh Config
| 
|
*/	
	public function Reload_realserver($vip,$ip,$servername="")
	{
		$str="<br>";
		$ServerInfo=$servername."*".$ip;
		exec($this->data['adminroot']."/Production_realserver.sh ".$ServerInfo." ".$vip, $ar, $status);
		for ($i=0; $i < count($ar);$i++)
			if ($i==0)
				$str.=str_replace('ffffff', 'green',$ar[$i])."<br>";
			else
				$str.=$ar[$i]."<br>";
		$str = substr($str,0,strlen($str)-4);
		echo "<table width=\"300\"  border=\"0\" cellpadding=\"2\" cellspacing=\"1\" bgcolor=\"#006699\"><tr height=50 align=center bgcolor=\"#DFFFFF\"><td><font color=green>".$str."</font></td></tr></table>\n";

	}


/*
|--------------------------------------------------------------------------
|   Performance img;
|--------------------------------------------------------------------------
|
|  Performance img
| 
|
*/	
	public function Performance($type="",$lvsip="",$ip="")
	{
		header("Cache-Control: max-age=120, must-revalidate");
		$this->data['PerformanceIMG']="";
		if ($type=="lvsip")
		{
			if ($lvsip=="")
			{
				$Condition["state"]= 'MASTER';
				$results=$this->admin_model->get_datacenter_master($Condition);
				if (!$results)
				{
				        show_error("连接数据库出错，请与管理员联系。");
				}
				else
				{
					foreach($results->result() as $myrow)
					{
						$this->data['PerformanceIMG'].=getPerformance("lvsip",$myrow->wip,"");
					}
					
				}
			}
			else	$this->data['PerformanceIMG'].=getPerformance("lvsip",$lvsip,"");
			
		}elseif ($type=="vip")
			$this->data['PerformanceIMG'].=getPerformance("vip",$lvsip,$ip);
		elseif ($type=="server")
			$this->data['PerformanceIMG'].=getPerformance("server",$this->admin_model->get_server_datacenterip($ip),$ip);
		$this->load->view('Performance_view', $this->data);
	}


/*
|--------------------------------------------------------------------------
|  update Monitors enbale/disable page;
|--------------------------------------------------------------------------
|
| update Monitors page;.
| 
|
*/	
	public function Servers_do_Condition()
	{             
                if ($this->phpsession->get('adminsession_user_id')=="zhiban")
                {
                       show_error("对不起，值班帐号只能浏览，不能操作!");
                }  
                if (empty($_POST['selected_id']) || strlen($_POST['auditing'])==0)
                        show_error("/lvs/Servers|".$this->lang->line('admin_noselect'));
                else
                {
                        $this->Condition=$_POST['selected_id'];
                        $getaudi=$_POST['auditing'];
                }
                                             
                $this->admin_model->set_update('ty_lvs_servers',$this->Condition,'weight',$getaudi);
		redirect('/lvs/Servers');
	}
	

/*
|--------------------------------------------------------------------------
|   hosts file;
|--------------------------------------------------------------------------
|
|  Linux server hosts file;
| 
|
*/	
	public function hosts()
	{
		$this->data['datacenter']=$this->admin_model->get_datacenter_hosts();
		$this->data['servercenter']=$this->admin_model->get_server_hosts();
		$this->load->view('hosts_view', $this->data);
	}


/*
|--------------------------------------------------------------------------
|   check hosts;
|--------------------------------------------------------------------------
|
|  check hosts file;
| 
|
*/	
	public function check()
	{
		$this->load->view('check_view', $this->data);
	}
	
/*
|--------------------------------------------------------------------------
|   check hosts;
|--------------------------------------------------------------------------
|
|  check hosts file;
| 
|
*/	
	public function check_do()
	{
		$hosts_string="";
		$str="";
		$datacenter=$this->admin_model->get_datacenter_hosts();
		$servercenter=$this->admin_model->get_server_hosts();
		foreach($datacenter->result() as $myrow)
		{
			$hosts_string.=$myrow->servername."\;";
		}
	
		foreach($servercenter->result() as $myrow1)
		{
			$hosts_string.=$myrow1->servername."\;";
		}
		$hosts_string=substr($hosts_string,0,strlen($hosts_string)-2);
		exec($this->data['adminroot']."/check.sh ".$hosts_string, $ar, $status);
		for ($i=0; $i < count($ar);$i++)
		{
			$str.=$ar[$i]."<br>";
		}
		echo "<table width=\"98%\"  border=\"0\" cellpadding=\"2\" cellspacing=\"1\" bgcolor=\"#999999\"><tr height=50 align=left bgcolor=\"#ffffff\"><td><font color=green>".$str."</font></td></tr></table>\n";		
	}
}
